import React, { Fragment, useLayoutEffect, useEffect, useState, useRef } from 'react';
import { Timeline, Spin, message, Empty, DatePicker, Button } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import InfiniteScroll from 'react-infinite-scroller';
import cmdbres from '@/data/cmdbres';
import request from '@/utils/request';
import hcpUtils from '@/utils/hcpUtils';
import moment from 'moment';
import './index.less';

const toTimeStr = (momentInput, { fn, formatStr = 'YYYY-MM-DD HH:mm:ss' } = {}) => {
    const cloned = moment(momentInput);
    if (cloned.isValid()) return (fn ? fn(cloned) : cloned).format(formatStr);
    return '';
};

const { RangePicker } = DatePicker;
const ModelLogs = ({ moduleId, modelInfo }) => {
    const [info, setInfo] = useState([]);
    const [loading, setLoading] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const [skip, setSkip] = useState(1);
    const [limit, setLimit] = useState(10);
    const [date, setDate] = useState([hcpUtils.timeConversion(modelInfo?.createTime), moment()]);
    const maxNumberRef = useRef();

    useLayoutEffect(() => {
        if (moduleId) getHistory(true);
    }, [moduleId]);

    const onTimeChange = (dates, dateString) => {
        setDate(dates);
        setHasMore(true);
        setSkip(1);
    };

    useEffect(() => {
        if (skip !== 1) getHistory(false);
    }, [skip, limit]);

    const getHistory = async (init) => {
        setLoading(true);
        const res = await request({
            ...cmdbres.queryModelLog,
            data: {
                platformCode: 'omp',
                moduleCode: 'CMDB',
                page: skip,
                pageSize: limit,
                resourceId: moduleId,
                beginTime: date ? toTimeStr(date[0], { fn: (m) => m.startOf('day') }) : undefined,
                endTime: date ? toTimeStr(date[1], { fn: (m) => m.endOf('day') }) : undefined,
            },
        });
        setLoading(false);
        if (res && res.data) {
            res.data.list.map((i, index) => (i.key = index));
            if (init) {
                setInfo(res.data.list);
            } else {
                setInfo((inf) => {
                    const l = inf.concat(res.data.list);
                    return l;
                });
            }
            maxNumberRef.current = res.data.total;
        } else {
            setInfo([]);
        }
    };

    const handleInfiniteOnLoad = () => {
        setLoading(true);
        if (skip * limit >= maxNumberRef.current) {
            message.warning('已加载全部记录！');
            setHasMore(false);
            setLoading(false);
            return;
        }
        setSkip((sk) => {
            return sk + 1;
        });
    };
    const content = (item, index) => (
        <Timeline.Item key={index}>
            <div className="alarm-info-item">
                <p>
                    <span className="alarm-info-card-content">
                        {item?.operateTime ? toTimeStr(item?.operateTime) : '-'}
                    </span>
                </p>
                <p>
                    <span className="alarm-info-card-label">操作人：</span>
                    <span className="alarm-info-card-content">{item?.operator ?? '-'}</span>
                </p>
                <p>
                    <span className="alarm-info-card-content">{item?.operatorName}</span>
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <span className="alarm-info-card-content">「{item?.remarks}」</span>
                </p>
            </div>
        </Timeline.Item>
    );

    return (
        <Fragment>
            <div className="time-box">
                <span className="name">变更时间：</span>
                <RangePicker format="YYYY-MM-DD" onChange={onTimeChange} allowClear value={date} />
                <Button
                    style={{ marginLeft: 10 }}
                    icon={<SearchOutlined />}
                    onClick={() => {
                        getHistory(true);
                    }}
                />
            </div>
            <div className="infinite-box">
                <InfiniteScroll
                    initialLoad={false}
                    pageStart={0}
                    loadMore={handleInfiniteOnLoad}
                    hasMore={!loading && hasMore}
                    useWindow={false}
                    threshold={10}
                >
                    <Timeline>
                        {info.length ? (
                            info.map((v, i) => content(v, i))
                        ) : (
                            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                        )}
                        {loading ? <Spin /> : null}
                    </Timeline>
                </InfiniteScroll>
            </div>
        </Fragment>
    );
};

export default ModelLogs;
